import { LineChart,PieChart,ScatterChart,BarChart, LineSeriesOption } from 'echarts/charts';
import {
  GridComponent,
  GridComponentOption,
  TooltipComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { CSSProperties, FC, useEffect, useRef } from 'react';

echarts.use([
  GridComponent,
  ScatterChart,
  BarChart,
  PieChart,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  TooltipComponent,
]);

type EChartsOption = echarts.ComposeOption<
  GridComponentOption | LineSeriesOption
>;

type EchartsProps = {
  option: EChartsOption;
  style?: CSSProperties;
  loading?: boolean;
};

const EchartsComponent: FC<EchartsProps> = ({ option, style, loading }) => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (chartRef.current && option) {
      const chart = echarts.init(chartRef.current);
      chart.showLoading();
      chart.setOption(option);
      if (!loading) {
        chart.hideLoading();
      }

      return () => {
        chart.dispose();
      };
    }
  }, [option, loading]);

  return <div ref={chartRef} style={style} />;
};

export default EchartsComponent;
